<?php


namespace app\api\services;

use app\api\cache\CommunityCache;
use app\api\cache\KeysUtil;
use app\api\cache\Marketing;
use app\api\cache\RedisCache;
use app\api\consDir\CommunityConst;
use app\api\consDir\ErrorConst;
use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\consDir\ValConst;
use app\common\libs\Singleton;
use app\common\models\Community\Community;
use app\common\models\Community\CommunityBusiness;
use app\common\models\Community\CommunityCate;
use app\common\models\Community\CommunityConfig;
use app\common\models\Community\CommunityFission;
use app\common\models\Community\CommunityGoods;
use app\common\models\Community\CommunityLockLog;
use app\common\models\Community\CommunityOpOrder;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunitySignUser;
use app\common\models\Community\CommunityTaskLog;
use app\common\models\Community\CommunityTasksLog;
use app\common\models\Community\CommunityTrainingUser;
use app\common\models\Community\CommunityUser;
use app\common\models\Community\CommunityUserInfo;
use app\common\models\Community\CommunityWithdraw;
use app\common\models\Community\OperateActivity;
use app\common\models\Community\OperateActivityData;
use app\common\models\Community\PrepayCommunityOrder;
use app\common\models\Member\Finance;
use app\common\models\Member\Member;
use app\common\models\Member\MemberAgency;
use app\common\models\Member\MemberCommunityAmountLog;
use app\common\models\Member\MemberGxzLog;
use app\common\models\Member\MemberNum;
use app\common\models\Member\MemberWithdraw;
use app\common\models\Order\OrderError;
use app\common\models\Order\OrderPay;
use app\common\models\Order\OrderShop;
use app\common\models\Shop\Shop;
use app\common\utils\CommonUtil;
use think\Exception;
use think\facade\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class CommunityService
{
    use Singleton;

    /**
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function userCanRush($userId): bool
    {
        $userInfo = RedisCache::hGetAll(KeysUtil::getMemberInfoKey($userId));
        if (empty($userInfo)) {
            $arr = Member::getInstance()->where('id', $userId)->find()->toArray();
            $userInfo = CommonUtil::camelToUnderLine($arr);
            RedisCache::hMSet(KeysUtil::getMemberInfoKey($userId), $userInfo);
        }
        //培训用户
        $where = [
            ['user_id', '=', $userId],
            ['is_deleted', '=', 0],
        ];
        $num = CommunityTrainingUser::getInstance()->where($where)->value('buynum') ?? 0;
        $dayNum = $num > 0 ? bcdiv($num, 7) : 0;
        //获取用户购买社区个数
        $where = [
            ['user_id', '=', $userId],
            ['lock_status', '=', CommunityConst::LOCK],
            ['community_status','<>',8]
        ];
        $userCommunity = CommunityUser::getInstance()->where($where)->count();
        //判断次数
        $canCount = $num > 0 ? $num : $userInfo['can_count'];
        if ($userCommunity >= $canCount) {
            return false;
        }
        //判断每日次数
        $where = [
            ['user_id', '=', $userId],
            ['last_enter_time', '>', date('Y-m-d')],
        ];
        $communityCount = CommunityUser::getInstance()->where($where)->count();
        $everyDayCount = $dayNum > 0 ? $dayNum : $userInfo['every_day_count'];
        if ($communityCount >= $everyDayCount) {
            return false;
        }
        return true;
    }

    /**
     *
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function userCanCount($userId): bool
    {
        $userInfo = Member::getInstance()->where('id', $userId)->find();
        if (empty($userInfo)) {
            return false;
        }
        $isPartner = $userInfo['is_partner'];
        //每日抢购次数
        $everyDayCount = 0;
        //是否是普通会员
        $isCommon = 0;
        if ($isPartner > 0) {
            $userNum = $this->getCommunityConfig('servicer_num');
            $everyDayCount = $this->getCommunityConfig('servicer_user_num_day');
        } elseif ($userInfo['is_vip'] == CommunityConst::VIP_YES) {
            $userNum = $this->getCommunityConfig('vip_user_num');
            $everyDayCount = $this->getCommunityConfig('vip_user_num_day');
        } else {
            $isCommon = 1;
            $userNum = $this->getCommunityConfig('user_num');
            //普通会员每天次数
            $everyDayCount = $this->getCommunityConfig('user_num_day');
        }
        //邀请一人获得次数
        $inviteNum = $this->getCommunityConfig('invite_num');
        $inviteUserCount = MemberService::getInstance()->getDirectMembers($userId);
        //直推数量
        $inviteCount = bcmul($inviteNum, $inviteUserCount);
        //直推数量最大次数 14
        //$inviteCount = min($inviteCount, 14);
        $inviteCount = min($inviteCount, 7);
        $allCount = bcadd($userNum, $inviteCount);

        //普通会员有直推人
        if ($isCommon && $inviteUserCount) {
            //普通会员推荐每日次数 user_num_invite_day
            $everyDayCount = $this->getCommunityConfig('user_num_invite_day');
        }

        //额外奖励次数
        $extraNum = $this->getCommunityConfig('extra_num');
        $allCount = bcadd($allCount, $extraNum);

        $userInfo->canCount = $allCount;
        $userInfo->everyDayCount = $everyDayCount;
        $userInfo->save();
        $userData = $userInfo->toArray();
        $userData = CommonUtil::camelToUnderLine($userData);
        RedisCache::hMSet(KeysUtil::getMemberInfoKey($userData['id']), $userData);
        return true;
    }


    public function userBusinessInfo($userId): array
    {
        $where = [
            ['user_id', '=', $userId],
            ['status', '=', 1],
            ['deleted', '=', 0],
        ];
        $business = CommunityBusiness::getInstance()->where($where)->find();
        return empty($business) ? [] : $business->toArray();
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function splitCommunity($lastCommunityOrder, $price, $opPrice, $opOrderNo): bool
    {
        $where = [
            ['deleted', '=', 0]
        ];
        $community = CommunityFission::getInstance()->where($where)->find();
        if (!empty($community)) {
            CommunityFission::getInstance()->where('id', $community['id'])->update(['deleted' => 1, 'update_at' => date('Y-m-d H:i:s')]);
        }
        if (empty($community)) {
            $rushCity = $this->getCommunityConfig('rush_city');

            $where = [
                ['city', '=', $rushCity],
                ['lock_status', '=', CommunityConst::LOCK],
                ['deleted', '=', 0],
            ];
            $community = Community::getInstance()->where($where)->order('id desc')->find();
            if (empty($community)) {
                $where = [
                    ['lock_status', '=', CommunityConst::LOCK],
                    ['deleted', '=', 0],
                ];
                $community = Community::getInstance()->where($where)->order('id desc')->find();
            }
        }


        $community = empty($community) ? [] : $community->toArray();

        if (!empty($community)) {
            $data = [
                'lock_status' => CommunityConst::UNLOCK,
            ];
            Community::getInstance()->where('id', $community['id'])->update($data);
            $orderNo = $this->splitCommunityOp($opOrderNo, $community['id']);
            $data = [
                'community_name' => $community['name'],
                'community_id' => $community['id'],
                'address' => $community['province'] . $community['city'] . $community['country'] . $community['street'],
                'user_ids' => ';' . $lastCommunityOrder['userId'] . ';',
                'user_id' => $lastCommunityOrder['userId'],
                'last_enter_amount' => $price,
                'community_status' => CommunityConst::RELEASE_STATUS,
                'lock_status' => CommunityConst::LOCK,
                'last_order_id' => $lastCommunityOrder['id'],
                'is_pay_service' => 0,
                'total_amount' => $price,
                'op_price' => $opPrice,
                'op_order_no' => $orderNo,
                'activity_id' => 0,
            ];

            $ret = CommunityUser::getInstance()->where('community_id', $community['id'])->find();
            if (!empty($ret)) {
                //裂变已放社区 更新
                CommunityUser::getInstance()->where('community_id', $community['id'])->update($data);
            } else {
                CommunityUser::getInstance()->insert($data);
            }
        }
        return true;
    }

    /**
     * 转让拆单
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function splitCommunityOp($orderNo, $communityId)
    {
        $communityOpOrder = CommunityOpOrder::getInstance()->where('order_no', $orderNo)->find();
        if (empty($communityOpOrder)) {
            return '';
        }
        $data = [
            'community_id' => $communityId,
            'order_id' => $communityOpOrder['orderId'],
            'pay_price' => bcmul($communityOpOrder['payPrice'], 0.5, 2),
            'rate' => $communityOpOrder['rate'],
            'community_price' => bcmul($communityOpOrder['communityPrice'], 0.5, 2),
            'user_id' => $communityOpOrder['user_id'],
            'image' => $communityOpOrder['image'],
            'sign_image' => $communityOpOrder['signImage'],
            'order_no' => getNo('OP'),
            'create_at' => date('Y-m-d H:i:s'),
            'premium' => bcmul($communityOpOrder['premium'], 0.5, 2),
            'is_pay' => $communityOpOrder['isPay'],
            'pay_at' => $communityOpOrder['payAt'],
            'service_rate' => $communityOpOrder['serviceRate'],
        ];

        //更新旧的转让订单金额
        $communityOpOrder->payPrice = $data['pay_price'];
        $communityOpOrder->communityPrice = $data['community_price'];
        $communityOpOrder->premium = $data['premium'];
        $ret = $communityOpOrder->save();
        if (!$ret) {
            return '';
        }
        $ret = CommunityOpOrder::getInstance()->insert($data);
        if (!$ret) {
            return '';
        }
        return $data['order_no'];
    }


    /**
     * @param $communityId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunity($communityId): array
    {
        $where = [
            ['id', '=', $communityId]
        ];
        $community = Community::getInstance()->where($where)->find();
        return empty($community) ? [] : $community->toArray();
    }

    /**
     * @param $payInfo
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function getCommunityInviteMoney($payInfo): bool
    {
        $order = $this->getOrder($payInfo['orderNo']);
        if (empty($order)) {
            return false;
        }
        $orderNo = $payInfo['orderNo'];
        CommunityUser::getInstance()->where(['community_id' => $order['communityId']])->inc('user_amount', $order['premium']);
        if (!$order['lastOrderId']) {
            return false;
        }
        $lastOrder = $this->getLastCommunityOrder($order['lastOrderId']);
        if (empty($lastOrder)) {
            return false;
        }
        //上次购买本金、收益转余额
        $msg = "社区转让，获得购买本金";
        $price = $lastOrder['totalAmount'];
        $premium = $order['premium'];
        //裂变订单 本金、溢价收益拆分
        if ($lastOrder['isFission']) {
            $price = bcmul($lastOrder['totalAmount'], 0.5, 2);
        }
        Log::info($orderNo . '获得购买本金' . $price);
        //杉德支付，本金兑换到电子钱包
        MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'community_principal', $price, 1, $msg, $orderNo);
        $msg = "兑换到电子钱包";
        MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'change_bag', $price, 1, $msg, $orderNo);

        //社区溢价收益
        $serviceEarnings = $this->getCommunityConfig('member_settlement_rate');

        //提升社区溢价收益比例
        $improve = $this->improveRate($lastOrder['userId'],$lastOrder['id']);
        $improveRate = !empty($improve[0]) ? $improve[0] : 0;
        $serviceEarnings = $serviceEarnings + $improveRate;

        $msg = "社区转让，获得社区溢价收益，收益比例" . $serviceEarnings . '%，转让订单' . $orderNo . '，';
        $premiumPrice = bcmul(bcmul($premium, $serviceEarnings, 4), 0.01, 4);
        MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'community_premium', $premiumPrice, 3, $msg, $orderNo);

        //社区绿色积分，兑换到电子钱包，兑换记录ID,当前社区绿色积分
        //$msg = '兑换到电子钱包';
        //MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'change_bag', $premiumPrice, 3, $msg, $orderNo);

        Log::info($orderNo . '社区溢价收益' . $premiumPrice);

        //赠送贡献值
        $msg = '社区竞拍，赠送贡献值，订单' . $payInfo['orderNo'];
        MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'community', $premium, 7, $msg, $payInfo['orderNo']);
        //加入分润池
        MemberService::getInstance()->profitPoolLog($order['userId'], $order['price'], $orderNo, $premium, 4);

        //余额支付 公司杉德账号转账给用户
        if ($payInfo['payStatus'] == 3) {
            //扣除溢价收益8%手续费
            //$feeRate = CommunityService::getInstance()->getCommunityConfig('withdraw_fee');
            //$fee = bcmul($premiumPrice, bcmul($feeRate, 0.01, 2), 2);
            //$price = bcadd($price, bcsub($premiumPrice, $fee, 2), 2);
            //$price = bcadd($price, bcsub($premiumPrice, $fee, 2), 2);
            Log::info($orderNo . '余额支付，公司杉德账号转账给用户' . $price);
            $price = env('test.is_test') ? 0.01 : $price;
            $ret = SandService::getInstance()->transfer($price, env('sand.consumeMid'), SandConst::PREFIX . $lastOrder['userId'], 0, getNo(OrderPrefixConst::TR));
            if (!isset($ret['code']) || $ret['code'] != 1) {
                throw new Exception($orderNo . $ret['data']);
            }
        }

        if ($payInfo['payStatus'] == 4) {
            if ($order['isEnough']) {
                //扣除溢价收益8%手续费
                //$feeRate = CommunityService::getInstance()->getCommunityConfig('withdraw_fee');
                //$fee = bcmul($premiumPrice, bcmul($feeRate, 0.01, 2), 2);
                //$price = bcadd($price, bcsub($premiumPrice, $fee, 2), 2);
                Log::info($orderNo . '上个用户不足以支付，公司杉德账号转账给用户' . $price);
                $price = env('test.is_test') ? 0.01 : $price;
                $ret = SandService::getInstance()->transfer($price, env('sand.consumeMid'), SandConst::PREFIX . $lastOrder['userId'], 0, getNo(OrderPrefixConst::TR));
                if (!isset($ret['code']) || $ret['code'] != 1) {
                    throw new Exception($orderNo . $ret['data']);
                }
            } else {
                //用户支付后需要杉德确认转账
                Log::info($orderNo . '杉德确认转账金额' . $payInfo['payPrice']);
                $amount = env('test.is_test') ? 0.01 : $payInfo['payPrice'];
                $ret = SandService::getInstance()->transferConfirm(getNo(OrderPrefixConst::TC), $payInfo['payNo'], $amount, 'confirm', SandConst::PREFIX . $lastOrder['userId']);
                Log::info($orderNo . '杉德确认转账返回' . json_encode($ret, 256));
                if (!isset($ret['resultStatus']) || $ret['resultStatus'] != 'success') {
                    throw new Exception($orderNo . $ret['errorDesc']);
                }
            }
        }

        return true;
    }

    /**
     * 社区溢价分红 支付服务费后分红
     * @param $opOrder
     * @param $orderNo
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function dividend($opOrder, $orderNo): bool
    {
        $where = [
            'community_id' => $opOrder['communityId'],
        ];
        $order = CommunityOrder::getInstance()->where($where)->where('pay_at', 'not null')->order('id desc')->find();
        if (empty($order)) {
            return false;
        }
        //服务商收益
        //获取服务商
        $partnerInfo = MemberService::getInstance()->getMyPartnerInfo($order['userId']);
        if ($partnerInfo) {
            //获取服务商溢出收益百分比
            $serviceEarnings = $this->getCommunityConfig('service_earnings');
            $serviceEarnings = $this->getServiceRate($partnerInfo['partnerId'], $serviceEarnings);
            $msg = "社区转让，获得服务商收益，收益比例" . $serviceEarnings . '%，';
            $price = bcmul(bcmul($order['premium'], $serviceEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['partnerId'], 'service_earnings', $price, 3, $msg, $orderNo);
        }

        $member = Member::getInstance()->where('id', $order['userId'])->find();
        if (empty($member)) {
            return false;
        }

        //下级服务商团队社区溢价的2%举例说明:关系 A->B->C->D A,C 为服务商 ，D买了一个溢价社区，C拿溢价的8% A溢价的2%
        $myPartner = MemberService::getInstance()->getMyPartner($member);
        if ($myPartner) {
            //获取服务商团队溢出收益百分比
            $serviceTeamEarnings = $this->getCommunityConfig('service_team_earnings');
            $msg = "社区转让，获得服务商团队收益，收益比例" . $serviceTeamEarnings . '%，';
            $price = bcmul(bcmul($order['premium'], $serviceTeamEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($myPartner['id'], 'service_team_earnings', $price, 3, $msg, $orderNo);
        }

        CommunityOrder::getInstance()->where(['id' => $order['lastOrderId']])->update(['next_order_id' => $order['id']]);

        //省市区收益
        //获取社区的省市区代 极差
        $communityPartnerInfo = MemberService::getInstance()->getCommunityAgencyInfo($order['communityId']);
        if(!empty($communityPartnerInfo)){
            if ($communityPartnerInfo['provinceUid'] > 0) {
                //$provinceEarnings = $communityPartnerInfo['provinceEarnings'];
                $provinceEarnings = CommunityService::getInstance()->getCommunityConfig('province_community_earnings');
                $msg = "社区转让，获得区域（" . $communityPartnerInfo['provinceName'] . "）社区转让收益，收益比例" . $provinceEarnings . '%，转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $provinceEarnings, 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($communityPartnerInfo['provinceUid'], 'province_community_earnings', $price, 3, $msg, $orderNo);
            }
            if ($communityPartnerInfo['cityUid'] > 0) {
                //$cityEarnings = $communityPartnerInfo['cityEarnings'];
                $cityEarnings = CommunityService::getInstance()->getCommunityConfig('city_community_earnings');
                $msg = "社区转让，获得区域（" . $communityPartnerInfo['cityName'] . "）社区转让收益，收益比例" . $cityEarnings . '%，转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $cityEarnings, 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($communityPartnerInfo['cityUid'], 'city_community_earnings', $price, 3, $msg, $orderNo);
            }
            if ($communityPartnerInfo['countryUid'] > 0) {
                //$areaEarnings = $communityPartnerInfo['areaEarnings'];
                $areaEarnings = CommunityService::getInstance()->getCommunityConfig('area_community_earnings');
                $msg = "社区转让，获得区域（" . $communityPartnerInfo['countryName'] . "）社区转让收益，收益比例" . $areaEarnings . '%,转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $areaEarnings, 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($communityPartnerInfo['countryUid'], 'area_community_earnings', $price, 3, $msg, $orderNo);
            }
        }


        //获取用户的省市区代 极差
        $partnerInfo = MemberService::getInstance()->getMyAgencyInfo($opOrder['payUserId']);
        if ($partnerInfo['provinceUid'] > 0) {
            //$provinceEarnings = $partnerInfo['provinceEarnings'];
            $provinceEarnings = CommunityService::getInstance()->getCommunityConfig('province_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['provinceName'] . "）会员竞拍收益，收益比例" . $provinceEarnings . '%，转让订单' . $orderNo . ',';
            $price = bcmul(bcmul($order['premium'], $provinceEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['provinceUid'], 'province_user_earnings', $price, 3, $msg, $orderNo);
        }
        if ($partnerInfo['cityUid'] > 0) {
            //$cityEarnings = $partnerInfo['cityEarnings'];
            $cityEarnings = CommunityService::getInstance()->getCommunityConfig('city_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['cityName'] . "）会员竞拍收益，收益比例" . $cityEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $cityEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['cityUid'], 'city_user_earnings', $price, 3, $msg, $orderNo);
        }
        if ($partnerInfo['countryUid'] > 0) {
            //$areaEarnings = $partnerInfo['areaEarnings'];
            $areaEarnings = CommunityService::getInstance()->getCommunityConfig('area_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['countryName'] . "）会员竞拍收益，收益比例" . $areaEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $areaEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['countryUid'], 'area_user_earnings', $price, 3, $msg, $orderNo);
        }

        //事业部收益获取事业部列表 弃用
        /*$businessList = $this->getUserBusinessUser();
        foreach ($businessList as $val) {
            $incomeRate = $val['incomeRate'];
            $msg = "社区转让，获得事业部收益，收益比例" . $incomeRate . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $incomeRate, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($val['userId'], 'business_earnings', $price, 3, $msg, $orderNo);
        }*/

        //vip用户收益
        $inviteId = RedisCache::hGet(KeysUtil::getMemberInfoKey($order['userId']), 'invite_id');
        $vipUser = $this->getParentVipUser($inviteId);
        $vipEarnings = $this->getCommunityConfig('vip_earnings');
        if ($vipUser) {
            $msg = "社区转让，获得VIP收益，收益比例" . $vipEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $vipEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($vipUser['id'], 'vip_earnings', $price, 3, $msg, $orderNo);
        }

        //增加社区合伙人相关权益 直推会员抢社区，获得溢价中的3%，社区区域下会员抢社区获得1%收益
        $inviteUser = Member::getInstance()->where('id',$member['inviteId'])->find();
        //与服务商直推的收益是否叠加
        $partnerStatus = $this->getCommunityConfig('partner_status');
        if(!empty($inviteUser)){
            if(($inviteUser['isPartner'] == 1 && $partnerStatus == 1 && $inviteUser['partnerStatus'] == 1) || !$inviteUser['isPartner']){
                $where = [
                    ['user_id','=',$member['inviteId']],
                    ['community_status','=',CommunityConst::PERMANENT_STATUS],
                ];
                $communityUser = CommunityUser::getInstance()->where($where)->find();
                if($communityUser){
                    $earnings = $this->getCommunityConfig('direct_member_earnings');
                    $msg = "社区转让，获得直推会员社区溢价收益，收益比例" . $earnings . '%，转让订单' . $orderNo . '，';
                    $price = bcmul(bcmul($order['premium'], $earnings, 4), 0.01, 4);
                    if($member['inviteId']){
                        MemberService::getInstance()->addFinanceLog($member['inviteId'], 'community_premium', $price, 3, $msg, $orderNo);
                        Log::info($orderNo . '直推会员社区溢价收益' . $price);
                    }
                }
            }
        }

        //社区区域下会员抢社区获得1%收益
        $community = Community::getInstance()->where('comm_id',$member['commId'])->find();
        if(!empty($community)){
            $where = [
                ['community_status','=',CommunityConst::PERMANENT_STATUS],
                ['community_id','=',$community['id']]
            ];
            $communityUser = CommunityUser::getInstance()->where($where)->find();
            if($communityUser){
                $earnings = $this->getCommunityConfig('community_area_member_earnings');
                $msg = "社区转让，获得区域下会员溢价收益，收益比例" . $earnings . '%，转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $earnings, 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($communityUser['userId'], 'area_user_earnings', $price, 3, $msg, $orderNo);
                Log::info($orderNo . '区域下会员溢价收益' . $price);
            }
        }

        //活动专区团队长奖励
        $where = [
            ['community_id','=',$opOrder['communityId']],
        ];
        $activityId = CommunityUser::getInstance()->where($where)->value('activity_id');
        $activity = RedisCache::hGetAll(KeysUtil::getCommunityActivityKey($activityId));
        if (!empty($activity) && !empty($activity['phone'])) {
            $userId = Member::getInstance()->where('phone',$activity['phone'])->value('id');
            if(!empty($activity['is_set_award']) && !empty($activity['rate']) && !empty($userId)){
                $msg = "社区转让，获得活动专区溢价收益，收益比例" . $activity['rate'] . '%，转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $activity['rate'], 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($userId, 'community_premium', $price, 3, $msg, $orderNo);
            }
        }
        //阶段活动
        $this->operateActivity($member,$inviteUser,$order,$orderNo);
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function operateActivity($member,$inviteUser,$order,$orderNo): bool
    {
        if(empty($inviteUser)){
            return false;
        }
        $where = [
            ['deleted','=',0],
            ['status','=',1],
            ['is_switch','=',1]
        ];
        $ret = OperateActivity::getInstance()->where($where)->find();
        if(empty($ret)){
            return false;
        }
        if($ret['userType'] == 1){
            $flag = $this->isLevel($ret['userLevel'],$inviteUser,$member);
            if(!$flag){
                return false;
            }
        }
        $now = date('Y-m-d H:i:s');
        if($now < $ret['startTime'] || $now > $ret['endTime']){
            return false;
        }

        if($member['createAt'] < $ret['startTime'] || $member['createAt'] > $ret['endTime']){
            return false;
        }

        //第一阶段奖励
        if(($now >= $ret['firstStageStart'] && $now<= $ret['firstStageEnd'])){
            $remark = '一阶段奖励';
            $earnings = $ret['firstStageAward'];
            $price = bcmul(bcmul($order['premium'], $earnings, 4), 0.01, 4);
            $msg = '新春积极参与活动奖励，直推会员'.$member['userName'].'参与竞拍，收益比例'.$earnings.'%，订单' . $orderNo . '，';
            MemberService::getInstance()->addFinanceLog($inviteUser['id'], 'operate_activity_earnings', $price, 3, $msg, $orderNo);
            $this->addOperateActivityData($ret,$member,$inviteUser,$order,$earnings,$price,$remark);
        }

        //第二阶段奖励
        if(($now >= $ret['twoStageStart'] && $now<= $ret['twoStageEnd'])){
            $earnings = $ret['twoStageAward'];
            //第一阶段是否完成任务
            $where = [
                ['invite_id','=',$member['id']],
                ['create_at','between',[$ret['firstStageStart'],$ret['firstStageEnd']]],
            ];
            $count = OperateActivityData::getInstance()->where($where)->count();
            $remark = '二阶段奖励';
            if($count > 0){
                $earnings = bcadd($earnings,$ret['twoStageOneAward'],2);
                $remark = '一、二阶段叠加奖励';
            }
            $price = bcmul(bcmul($order['premium'], $earnings, 4), 0.01, 4);
            $msg = '新春积极参与活动奖励，直推会员'.$member['userName'].'参与竞拍，收益比例'.$earnings.'%，订单' . $orderNo . '，';
            MemberService::getInstance()->addFinanceLog($inviteUser['id'], 'operate_activity_earnings', $price, 3, $msg, $orderNo);
            $this->addOperateActivityData($ret,$member,$inviteUser,$order,$earnings,$price,$remark);
        }

        //第三阶段奖励
        if(($now >= $ret['threeStageStart'] && $now<= $ret['threeStageEnd'])){
            $earnings = $ret['threeStageAward'];
            //第一阶段是否完成任务
            $where = [
                ['invite_id','=',$member['id']],
                ['create_at','between',[$ret['firstStageStart'],$ret['firstStageEnd']]],
            ];
            $oneCount = OperateActivityData::getInstance()->where($where)->count();
            //第二阶段是否完成任务
            $where = [
                ['invite_id','=',$member['id']],
                ['create_at','between',[$ret['twoStageStart'],$ret['twoStageEnd']]],
            ];
            $twoCount = OperateActivityData::getInstance()->where($where)->count();
            $remark = '三阶段奖励';
            if($oneCount > 0){
                $earnings = bcadd($earnings,$ret['threeStageOneAward'],2);
                $remark = '一、三阶段叠加奖励';
            }
            if($twoCount > 0){
                $earnings = bcadd($earnings,$ret['threeStageTwoAward'],2);
                $remark = '二、三阶段叠加奖励';
            }
            if($oneCount > 0 && $twoCount > 0){
                $remark = '一、二、三阶段叠加奖励';
            }
            $price = bcmul(bcmul($order['premium'], $earnings, 4), 0.01, 4);
            $msg = '新春积极参与活动奖励，直推会员'.$member['userName'].'参与竞拍，收益比例'.$earnings.'%，订单' . $orderNo . '，';
            MemberService::getInstance()->addFinanceLog($inviteUser['id'], 'operate_activity_earnings', $price, 3, $msg, $orderNo);
            $this->addOperateActivityData($ret,$member,$inviteUser,$order,$earnings,$price,$remark);
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function isLevel($userLevel, $inviteUser, $member): bool
    {
        if(empty($ret['userLevel'])){
            return false;
        }
        if(in_array(1,$userLevel)){
            return true;
        }
        $userLevel = json_decode($userLevel,true);
        $level = $inviteUser['isPartner'] ? 3 : 0;
        if(in_array($level,$userLevel)){
            return true;
        }
        $where = [
            ['status','=',1],
            ['deleted','=',0],
            ['user_id','=',$inviteUser['id']]
        ];
        $agencyType = MemberAgency::getInstance()->where($where)->value('agency_type');
        if($agencyType == 1){
            $level = 5;
        }elseif ($agencyType == 2){
            $level = 6;
        }else{
            $level = 7;
        }
        if(in_array($level,$userLevel)){
            return true;
        }
        $where = [
            ['user_id','=',$inviteUser['id']],
            ['community_status','=',CommunityConst::PERMANENT_STATUS]
        ];
        $level = CommunityUser::getInstance()->where($where)->count() ? 2 : 0;
        if(in_array($level,$userLevel)){
            return true;
        }
        $ping = MemberService::getInstance()->getMyPartner($member);
        $level = !empty($ping) ? 4 : 0;
        if(in_array($level,$userLevel) && !empty($ping) && $ping['id'] == $inviteUser['id']){
            return true;
        }
        return false;
    }

    public function addOperateActivityData($activity,$member,$inviteUser,$order,$earnings,$money,$remark): bool
    {
        $data = [
            'title' => $activity['title'],
            'user_id' => $inviteUser['id'],
            'invite_id' => $member['id'],
            'reg_time' => $member['createAt'],
            'join_time' => date('Y-m-d H:i:s'),
            'order_no' => $order['orderNo'],
            'price' => $order['totalAmount'],
            'premium' => $order['premium'],
            'rate' => $earnings,
            'phone' => $inviteUser['phone'],
            'activity_id' => $activity['id'],
            'community_id' => $order['communityId'],
            'money' => $money,
            'remark' => $remark,
        ];
        OperateActivityData::getInstance()->insert($data);
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getServiceRate($userId, $serviceEarnings){
        $serviceRate = Member::getInstance()->where('id',$userId)->value('service_rate');
        if(!empty($serviceRate)){
            return $serviceRate;
        }
        $data = Marketing::getKeyData('marketing', 'service_set');
        if(!empty($data)){
            if(isset($data['auto_status']) && $data['auto_status'] == 1){
                if(isset($data['check_type'])){
                    if($data['check_type'] == 1){
                        //上月
                        //直推参与社区人数
                        $startDate = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
                        $endDate = mktime(0, 0, 0, date("m"), 1, date("Y")) - 1;
                        $start = date('Y-m-d H:i:s', $startDate);
                        $end = date('Y-m-d H:i:s', $endDate);
                    }else{
                        //周
                        //上周
                        $startDate = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
                        $endDate = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
                        $start = date('Y-m-d H:i:s', $startDate);
                        $end = date('Y-m-d H:i:s', $endDate);
                    }
                    $where = [
                        ['m.invite_id','=',$userId],
                        ['o.status','=',CommunityConst::ORDER_PAY],
                        ['o.create_at','between', [$start, $end]]
                    ];
                    $inviteCommunityNum = CommunityOrder::getInstance()
                        ->alias('o')
                        ->leftJoin('member m','o.user_id=m.id')
                        ->where($where)
                        ->count();

                    //团队会员参与社区人数
                    $inviteTeamCommunityNum = CommunityOrder::getInstance()
                        ->alias('o')
                        ->leftJoin('member m','o.user_id=m.id')
                        ->whereLike('m.invite_ids','%-'.$userId.'-%')
                        ->where('o.create_at','between',[$start, $end])
                        ->where('o.status',CommunityConst::ORDER_PAY)
                        ->count('DISTINCT o.user_id');
                    if(!empty($data['check'])){
                        $checkRate = 0;
                        foreach($data['check'] as $v){
                            if($inviteCommunityNum >= $v['direct'] && $inviteTeamCommunityNum >= $v['team']){
                                $checkRate = $v['rate'];
                            }
                        }
                        if($checkRate > 0){
                            $serviceEarnings = $checkRate;
                        }
                    }
                }
            }
        }
        return $serviceEarnings;
    }

    public function getParentVipUser($parentUserId): array
    {
        $where = [
            ['is_vip', '=', CommunityConst::VIP_YES],
            ['status', '=', 1],
            ['id', '=', $parentUserId]
        ];
        $list = Member::getInstance()->where($where)->field('id')->find();
        return empty($list) ? [] : $list->toArray();
    }

    public function getUserBusinessUser(): array
    {
        $where = [
            ['status', '=', 1],
            ['deleted', '=', 0],
        ];
        $list = CommunityBusiness::getInstance()->where($where)->field('user_id,income_rate')->select();
        return empty($list) ? [] : $list->toArray();
    }

    /**
     * @param $lastOrderId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getLastCommunityOrder($lastOrderId): array
    {
        if (!$lastOrderId) {
            return [];
        }
        $where = [
            ['id', '=', $lastOrderId],
        ];
        $info = CommunityOrder::getInstance()->where($where)->find();
        return empty($info) ? [] : $info->toArray();
    }

    /**
     * @param $status
     * @param $type
     * @param $userId
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityUserLog($status, $type, $userId, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $userId],
            ['type', '=', 0],
        ];
        if ($status) {
            $where[] = ['status', '=', $status];
        }
        switch ($type) {
            case 1:
                $where[] = ['log_type', 'in', ['community_withdraw']];
                break;
            case 2:
                $where[] = ['log_type', 'in', ['community_premium']];
                break;
            case 3:
                $where[] = ['log_type', 'in', ['community_pay']];
                break;
            case 4:
                $where[] = ['log_type', 'in', ['sign_pay']];
                break;
            case 5:
            case 6:
            case 7:
            case 9:
                $where[] = ['log_type', 'in', ['sign_earnings']];
                break;
            case 8:
                $where[] = ['log_type', 'in', ['business_earnings']];
                break;
            case 10:
                $where[] = ['log_type', 'in', ['service_pay']];
                break;
            case 11:
                //$where[] = ['log_type', 'in', ['province_earnings', 'city_earnings', 'area_earnings']];
                $where[] = ['log_type', 'in', ['province_community_earnings', 'city_community_earnings', 'area_community_earnings']];
                break;
            case 12:
                $where[] = ['log_type', 'in', ['province_user_earnings', 'city_user_earnings', 'area_user_earnings']];
                break;
            case 13:
                $where[] = ['log_type', 'in', ['service_earnings', 'service_team_earnings']];
                break;
        }
        $field = 'amount,remark,status,create_at';
        $list = MemberCommunityAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->field($field)
            ->select();
        $list = empty($list) ? [] : $list->toArray();
        foreach ($list as &$v) {
            $v['remark'] = str_replace("当前绿色积分", "当前收益", $v['remark']);
        }
        return $list;
    }

    /**
     * @param $timeType
     * @param $page
     * @param $pageSize
     * @param $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunityUserRank($timeType, $page, $pageSize, $userId): array
    {
        //昨天
        $startDate = mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"));
        $endDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")) - 1;
        $lastStartDate = date('Y-m-d H:i:s', $startDate);
        $lastEndDate = date('Y-m-d H:i:s', $endDate);

        //上周
        $startDate = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
        $endDate = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
        $lastWeekStartDate = date('Y-m-d H:i:s', $startDate);
        $lastWeekEndDate = date('Y-m-d H:i:s', $endDate);

        //上月
        $startDate = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
        $endDate = mktime(0, 0, 0, date("m"), 1, date("Y")) - 1;
        $lastMonthStartDate = date('Y-m-d H:i:s', $startDate);
        $lastMonthEndDate = date('Y-m-d H:i:s', $endDate);
        $where = [
            ['c.status', '=', 1]
        ];
        if ($timeType == 1) {
            $where[] = ['c.create_at', 'between', [$lastStartDate, $lastEndDate]];
        }
        if ($timeType == 2) {
            $where[] = ['c.create_at', 'between', [$lastWeekStartDate, $lastWeekEndDate]];
        }
        if ($timeType == 3) {
            $where[] = ['c.create_at', 'between', [$lastMonthStartDate, $lastMonthEndDate]];
        }

        $infoSql = MemberCommunityAmountLog::getInstance()->alias('c')
            ->leftJoin('member u', 'c.user_id=u.id')
            ->where($where)
            ->field('c.user_id,sum(c.amount) amount,u.phone,u.user_name,u.avatar')
            ->group('c.user_id')
            ->order('amount desc')
            ->buildSql();
        Db::execute('SET @rank= 0;');
        $rankSql = Db::table($infoSql . ' g')
            ->field('(@rank:=@rank + 1) AS rank,g.*')
            ->buildSql();
        //列表数据
        $list = Db::table($rankSql . ' r')->page($page, $pageSize)->select();

        //我的排名
        Db::execute('SET @rank= 0;');
        $self = Db::table($rankSql . ' r')->where('r.user_id', $userId)->find();
        return ['rows' => $list, 'self' => $self];
    }

    /**
     * @param $timeType
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunityRank($timeType, $page, $pageSize): array
    {
        $field = 'shop_amount,shop_num,community_name,address';
        $list = CommunityUser::getInstance()
            ->order('shop_amount desc')
            ->page($page, $pageSize)
            ->field($field)
            ->select();
        return empty($list) ? [] : $list->toArray();
    }

    public function paySignByBalance($userId, $userSign)
    {
        CommunitySignUser::getInstance()->startTrans();
        try {
            $return = $this->callbackSign($userSign['orderNo']);
            if (!$return) {
                return false;
            }
            $msg = '支付签到订单，扣除余额：' . $userSign['payPrice'];
            MemberService::getInstance()->addFinanceLog($userId, 'sign_pay', $userSign['payPrice'], 3, $msg, $userSign['orderNo']);

        } catch (\Exception $e) {
            CommunitySignUser::getInstance()->rollback();
            return false;
        }
    }

    /**
     * @param $orderNo
     * @return CommunitySignUser
     */
    public function callbackSign($orderNo)
    {
        $where = [
            'order_no' => $orderNo,
            'order_status' => 1,
        ];
        return CommunitySignUser::getInstance()->where($where)->update(['order_status' => 2, 'pay_at' => date('Y-m-d H:i:s')]);

    }

    public function payOrderSign($userSign)
    {
        $payNo = getNo('SIPAY');
        $data = [
            'pay_price' => $userSign['payPrice'],
            'user_id' => $userSign['userId'],
            'order_no' => $userSign['orderNo'],
            'pay_no' => $payNo,
            'order_status' => 2,
            'expire_at' => date('Y-m-d H:i:s', strtotime('+1 minute')),
            'sign_price' => 0
        ];
        $payId = OrderPay::getInstance()->insertGetId($data);
        if (!$payId) {
            return false;
        }
        return $data;
    }


    public function getSign($orderNo): array
    {
        $where = [
            'order_no' => $orderNo,
            'order_status' => 1,
        ];
        $sign = CommunitySignUser::getInstance()->where($where)->find();
        return empty($sign) ? [] : $sign->toArray();
    }

    public function addCommunitySignOrder($userId, $payPrice): array
    {
        $orderNo = getNo('SO');
        $expireDate = CommunityService::getInstance()->getCommunityConfig('check_in_valid_time');
        $data = [
            'user_id' => $userId,
            'amount' => CommunityService::getInstance()->getCommunityConfig('check_in_fee'),
            'refund_amount' => CommunityService::getInstance()->getCommunityConfig('check_in_failed_award'),
            'community_amount' => CommunityService::getInstance()->getCommunityConfig('check_in_success_award'),
            'expire_at' => date('Y-m-d H:i:s', strtotime('+' . $expireDate . ' day')),
            'order_no' => $orderNo,
            'pay_price' => $payPrice,
        ];

        CommunitySignUser::getInstance()->insert($data);
        return $data;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function addCommunitySign($userId): bool
    {
        $sign = CommunityService::getInstance()->getUserBag($userId, 1);
        if (!empty($sign)) {
            return false;
        }
        $signTime = CommunityService::getInstance()->getSignTimes();
        $allSignCount = CommunityService::getInstance()->getCommunityConfig('check_in_max_num');

        $end = strtotime(date('Y-m-d 23:59:59')) - time();

        $where = [
            ['type','=',1],
            ['create_at', '>=', date('Y-m-d') . ' ' . $signTime['start']],
        ];
        $count = CommunitySignUser::getInstance()->where($where)->count();
        if($count >= $allSignCount){
            return false;
        }

        Log::error('count:'.$count.'allSignCount:'.$allSignCount);
        $expireDate = CommunityService::getInstance()->getCommunityConfig('check_in_valid_time');
        $data = [
            'user_id' => $userId,
            'amount' => CommunityService::getInstance()->getCommunityConfig('check_in_fee'),
            'refund_amount' => CommunityService::getInstance()->getCommunityConfig('check_in_failed_award'),
            'community_amount' => CommunityService::getInstance()->getCommunityConfig('check_in_success_award'),
            'expire_at' => date('Y-m-d H:i:s', strtotime('+' . $expireDate . ' day') - 3600),
            'order_status' => 2
        ];
        CommunitySignUser::getInstance()->insert($data);
        RedisCache::set(KeysUtil::getCommunitySignUserKey($userId),1,$end);
        return true;
    }

    /**
     * 获取下一次签到时间
     * @return string[]
     */
    public function getSignTimes(): array
    {
        $settlementTime = $this->getCommunityConfig('check_in_time');
        return $this->getTimeInfo($settlementTime);
    }

    /**
     * @param $payInfo
     * @param $data
     * @param $communityOrder
     * @param $communityUser
     * @return bool
     */
    public function payCallback($payInfo, $data, $communityOrder, $communityUser): bool
    {
        $date = date('Y-m-d H:i:s');
        $userIds = empty($communityUser['userIds']) ? (";" . $communityOrder['userId'] . ";") : ($communityUser['userIds'] . $communityOrder['userId'] . ";");
        $communityUserData = [
            'user_amount' => bcadd($communityUser['userAmount'], $communityOrder['premium'], 2),
            'user_ids' => $userIds,
            'community_status' => CommunityConst::OP_STATUS,
            'lock_status' => CommunityConst::LOCK,
            'user_id' => $communityOrder['userId'],
            'last_enter_amount' => $communityOrder['price'],
            'last_order_id' => $communityOrder['id'],
            'last_enter_time' => $date,
            'total_amount' => $communityOrder['totalAmount'],
            'update_at' => $date
        ];
        //新社区自动进入考核期
        if ($communityUser['lastEnterAmount'] == 0) {
            $this->addTransferCount($payInfo['userId'],$payInfo['orderNo']);
            $communityUserData['community_status'] = CommunityConst::CHECK_STATUS;
            $communityUserData['op_time'] = date('Y-m-d H:i:s');
        }

        $isCommunityUser = CommunityUser::getInstance()->where(['id' => $communityUser['id']])->update($communityUserData);
        if (!$isCommunityUser) {
            return false;
        }

        $orderDate = [
            'status' => CommunityConst::ORDER_PAY,
            'pay_at' => $date,
            'pay_price' => $payInfo['payPrice'],
            'amount_price' => $payInfo['communityPayAmount'],
            'sign_price' => $payInfo['signPrice'],
            'trade_no' => $data['trade_no'],
        ];
        $where = [
            ['order_no', '=', $payInfo['orderNo']],
            ['status', '=', CommunityConst::ORDER_NO_PAY]
        ];
        $isCommunityOrder = CommunityOrder::getInstance()->where($where)->update($orderDate);
        if (!$isCommunityOrder) {
            return false;
        }

        //更新社区订单
        $orderInfo = CommunityService::getInstance()->getOrder($payInfo['orderNo']);
        if($orderInfo){
            $orderData = CommonUtil::camelToUnderLine($orderInfo);
            $end = strtotime($orderInfo['expireAt']);
            $expire = $end - time();
            if($expire > 0){
                RedisCache::setEx(KeysUtil::getCommunityOrderKey($payInfo['orderNo']), $expire, json_encode($orderData));
            }
        }

        //删除可入住社区列表的社区
        if (in_array($communityUser['type'], [0, 1])) {
            RedisCache::zRem(KeysUtil::getCommunityPayListKey($communityUser['type']), $communityUser['communityId']);
        }

        //删除会议专区列表的社区
        if ($communityUser['type'] == 2) {
            RedisCache::zRem(KeysUtil::getCommunityMeetListKey($communityUser['activityId']), $communityUser['communityId']);
        }

        //更新社区
        $communityInfo = $this->getCommunityUser($communityUser['communityId']);
        RedisCache::hMSet(KeysUtil::getCommunityInfo($communityUser['communityId']), CommonUtil::camelToUnderLine($communityInfo));

        //删除社区支付中订单
        RedisCache::del(KeysUtil::getCommunityInPayOrderKey($communityUser['communityId']));

        //删除用户支付中订单
        RedisCache::del(KeysUtil::getCommunityUserInPayOrderKey($communityOrder['userId']));

        return true;
    }


    public function payOrder($orderInfo, $wechatPayPrice, $amountPrice, $signPrice, $type, $orderStatus = 1)
    {
        $payNo = getNo('COPAY');
        $data = [
            'pay_status' => $type,
            'pay_price' => $wechatPayPrice, //余额支付金额
            'user_id' => $orderInfo['user_id'],
            'order_no' => $orderInfo['order_no'],
            'pay_no' => $payNo,
            'community_pay_amount' => $amountPrice,
            'order_status' => $orderStatus,
            'expire_at' => date('Y-m-d H:i:s', strtotime('+15 minute')),
            'sign_price' => $signPrice
        ];
        $payId = OrderPay::getInstance()->insertGetId($data);
        if (!$payId) {
            return false;
        }
        return $data;
    }

    public function payOpOrder($orderInfo, $wechatPayPrice, $amountPrice, $signPrice, $type)
    {
        $payNo = getNo('OPPAY');
        $data = [
            'pay_status' => $type,
            'pay_price' => $wechatPayPrice, //余额支付金额
            'user_id' => $orderInfo['payUserId'],
            'order_no' => $orderInfo['orderNo'],
            'pay_no' => $payNo,
            'community_pay_amount' => $amountPrice,
            'order_status' => 4,
            'expire_at' => date('Y-m-d H:i:s', strtotime('+15 minute')),
            'sign_price' => $signPrice
        ];
        $payId = OrderPay::getInstance()->insertGetId($data);
        if (!$payId) {
            return false;
        }
        return $data;
    }

    public function getOrder($orderNo): array
    {
        $where = [
            ['order_no', '=', $orderNo],
        ];
        $order = CommunityOrder::getInstance()->where($where)->find();
        return empty($order) ? [] : $order->toArray();
    }

    public function getUserBag($userId,$type = 0): array
    {
        //$time = date('Y-m-d 00:00:00', strtotime('-2 day'));
        $where = [
            ['user_id', '=', $userId],
            ['order_status', '=', 2],
            ['sign_status', '=', 1],
            ['expire_at', '>', date('Y-m-d')]
        ];
        if($type > 0){
            $where[] = ['type','=',$type];
        }
        $info = CommunitySignUser::getInstance()->where($where)->field('id,community_amount')->order('expire_at desc')->find();
        return empty($info) ? [] : $info->toArray();
    }

    /**
     * 更新红包状态
     * @param $userId
     * @param $status 1未使用 2入驻已使用 3已返还到余额
     * @return bool
     */
    public function setUserBag($userId, $status): bool
    {
        $where = [
            ['user_id', '=', $userId],
            ['order_status', '=', 2],
            ['sign_status', '=', 1],
            ['expire_at', '>', date('Y-m-d')]
        ];
        $communitySignUser = CommunitySignUser::getInstance()->where($where)->order('expire_at asc')->find();
        $communitySignUser->sign_status = $status;
        return $communitySignUser->save();
    }

    public function getLastCommunity($communityId): array
    {
        $where = [
            ['community_id', '=', $communityId],
            ['status', '=', 2], //2已支付
        ];
        $return = CommunityOrder::getInstance()->where($where)->order('id desc')->field('id,user_id')->find();
        return empty($return) ? [] : $return->toArray();
    }

    public function createOrder($communityInfo, $uid, $lastOrder, $image, $signImage)
    {
        $timeout = CommunityService::getInstance()->getCommunityConfig('order_timeout');
        $prepayPrice = CommunityService::getInstance()->getPrepayPrice($communityInfo['community_id'],$uid);
        try {
            $data = [
                'user_id' => $uid,
                'community_id' => $communityInfo['community_id'],
                'last_order_id' => $lastOrder['id'] ?? 0,
                'order_no' => getNo('CO'),
                'price' => $communityInfo['price'],
                'expire_at' => date('Y-m-d H:i:s', strtotime("+{$timeout} minute")),
                'premium' => $communityInfo['premium'],
                'rate_week' => $communityInfo['rateWeek'],
                'settlement_rate' => $communityInfo['settlementRate'],
                'total_amount' => $communityInfo['totalAmount'],
                'type' => $communityInfo['type'],
                'image' => $image,
                'sign_image' => $signImage,
                'prepay_price' => $prepayPrice
            ];
            //mq生成订单
            $event["exchange"] = config('rabbitmq.community_order_queue');
            RabbitMqService::send($event, $data);
        } catch (\Exception $e) {
            return false;
        }
        $exTime = strtotime($data['expire_at']) - time();
        return ['orderNo' => $data['order_no'], 'expireAt' => $data['expire_at'], 'exTime' => $exTime];
    }

    public function dealOrder(array $data): bool
    {
        if (empty($data)) {
            return false;
        }
        $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($data['community_id']));
        if (!$communityInfo) {
            return false;
        }
        $communityUser = CommunityUser::getInstance()
            ->where(['community_id' => $communityInfo['community_id']])->find();
        if (!in_array($communityUser['communityStatus'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS])) {
            return false;
        }
        CommunityOrder::getInstance()->startTrans();
        try {
            $orderId = CommunityOrder::getInstance()->insertGetId($data);
            if (!$orderId) {
                CommunityOrder::getInstance()->rollback();
                return false;
            }
            //是否是第一次被抢购的社区
            $isFirst = $communityInfo['last_enter_amount'] > 0 ? 0 : 1;
            $updateData = [
                'community_status' => CommunityConst::BUY_STATUS,
                'is_first' => $isFirst,
                //'update_at' => date('Y-m-d H:i:s')
            ];
            $communityUser = CommunityUser::getInstance()
                ->where(['community_id' => $communityInfo['community_id']])
                ->update($updateData);
            if (!$communityUser) {
                CommunityOrder::getInstance()->rollback();
                return false;
            }
            $orderInfo = CommunityOrder::getInstance()->where('id', $orderId)->find()->toArray();
            $orderData = CommonUtil::camelToUnderLine($orderInfo);
            $end = strtotime($data['expire_at']);
            $expire = $end - time();
            //取消订单
            RabbitMqService::sendDelay(['type' => 'community_order', 'order_id' => $orderId], $expire);
            //保存订单信息
            RedisCache::setEx(KeysUtil::getCommunityOrderKey($data['order_no']), $expire, json_encode($orderData));
            //设置社区支付订单中
            RedisCache::setEx(KeysUtil::getCommunityInPayOrderKey($orderInfo['communityId']), $expire, $orderInfo['userId']);
            //设置用户支付订单中
            RedisCache::setEx(KeysUtil::getCommunityUserInPayOrderKey($orderInfo['userId']), $expire, $orderInfo['communityId']);
        } catch (\Exception $e) {
            CommunityOrder::getInstance()->rollback();
            return false;
        }
        CommunityOrder::getInstance()->commit();
        return true;
    }

    /**
     * 获取下一次入驻时间
     * @return string[]
     */
    public function getTimes(): array
    {
        $settlementTime = $this->getCommunityConfig('settlement_time');
        return $this->getTimeInfo($settlementTime);
    }

    public function getCommunityGoods()
    {
        $goods = CommunityCache::getGoodsInfo();
        if (empty($goods)) {
            $goods = CommunityGoods::getInstance()->where('1=1')->find();
            CommunityCache::setGoodsInfo($goods);
        }
        $goods['content'] = json_decode($goods['content'], true);
        return $goods;
    }

    public function getPrepayPrice($communityId,$userId){
        $where = [
            ['status', '=' ,2],
            ['is_final','=',0],
            ['community_id','=',$communityId],
            ['user_id','=',$userId],
            ['is_turn','=',0],
            ['is_refund','=',0]
        ];
        return PrepayCommunityOrder::getInstance()->where($where)->value('pay_price') ?: 0;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getCommunityPrice($totalAmount, $lastCommunityOrder): array
    {
        //获取百分比加价
        $settlementRate = $this->getCommunityConfig('settlement_rate');
        $settlementRate = $this->getSettlementRate($settlementRate, $lastCommunityOrder);

        if ($totalAmount == 0) {
            //初始价格 1000
            $settlementPrice = $this->getCommunityConfig('settlement_price');
            return [
                'price' => $settlementPrice,
                'rateWeek' => $settlementRate['rateWeek'],
                'settlementRate' => $settlementRate['settlementRate'],
                'premium' => 0,
                'totalAmount' => $settlementPrice,
            ];
        }

        $where = [
            ['community_id', '=', $lastCommunityOrder['communityId']]
        ];
        $communityOpOrder = CommunityOpOrder::getInstance()->where($where)->order('id desc')->find();
        if (empty($communityOpOrder)) {
            CommonUtil::throwException(ErrorConst::NO_COMMUNITY_ERROR, ErrorConst::NO_COMMUNITY_ERROR_MSG);
        }

        //溢价
        //$premium = bcmul(bcmul($totalAmount, $communityOpOrder['rate'], 2), 0.01, 2);
        $premium = round($totalAmount * $communityOpOrder['rate'] * 0.01, 2);
        //社区溢价收益比例
        //$memberSettlementRate = $this->getCommunityConfig('member_settlement_rate');

        //提升社区溢价收益比例
        //$improve = $this->improveRate($communityOpOrder['userId'],$lastCommunityOrder['id']);
        //$memberSettlementRate = $memberSettlementRate + $improve[0];
        $memberSettlementRate = 100 - $this->getCommunityConfig('transfer_rate');

        return [
            //'price' => bcadd($totalAmount, bcmul($premium, $memberSettlementRate * 0.01, 2), 2),
            'price' => round($totalAmount + ($premium * $memberSettlementRate * 0.01), 2),
            'rateWeek' => $settlementRate['rateWeek'],
            'settlementRate' => $communityOpOrder['rate'],
            'premium' => $premium,
            //'totalAmount' => bcadd($totalAmount, $premium, 2),
            'totalAmount' => round($totalAmount + $premium, 2),
        ];
    }

    public function getSettlementRate($settlementRate, $lastCommunityOrder): array
    {
        if (empty($lastCommunityOrder)) {
            return ['settlementRate' => 0, 'rateWeek' => -1];
        }
        if (!isset($settlementRate[$lastCommunityOrder['rateWeek'] + 1])) {
            return ['settlementRate' => $settlementRate[0], 'rateWeek' => 0];
        }
        return ['settlementRate' => $settlementRate[$lastCommunityOrder['rateWeek'] + 1], 'rateWeek' => $lastCommunityOrder['rateWeek'] + 1];
    }


    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getCommunityConfig($keys)
    {
        $config = CommunityCache::getConfigInfo($keys);
        if (empty($config)) {
            $where = ['key' => $keys];
            $config = CommunityConfig::getInstance()->where($where)->find()->toArray();
            if ($config['unit'] == 'json') {
                $config['value'] = json_decode($config['value'], true);
            }
            CommunityCache::setConfigInfo($keys, $config);
        }
        return $config['value'];
    }

    /**
     * @param $communityId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunityUser($communityId): array
    {
        $where = [
            ['community_id', '=', $communityId]
        ];
        $info = CommunityUser::getInstance()
            ->where($where)
            //->field('id,community_id,user_id,last_enter_amount,community_name,community_status,user_amount,user_ids,last_order_id,type,total_amount')
            ->find();
        return empty($info) ? [] : $info->toArray();
    }

    /**
     * 绿色积分提现到个人余额
     * @param $userId
     * @param $communityAmount
     * @return bool
     */
    public function withdrawCommunity($userId, $communityAmount, $type): bool
    {
        Finance::getInstance()->startTrans();
        try {
            //$percent = $this->getCommunityConfig('earnings_percent');
            $orderNo = getNo('CW');
            $withdrawType = [
                0 => 'greenpoints',
                1 => 'packspoints',
                2 => 'commission',
                3 => 'bonus',
            ];
            $percent = 0;
            $deduction = 0;
            $deductionRate = 0;
            $configSet = Marketing::getKeyData('withdraw', $withdrawType[$type]);
            if(!empty($configSet) && $configSet['status'] == 1){
                $percent = $configSet['premium'];
                if($configSet['community_deduction_rate'] > 0){
                    $deductionRate = $configSet['community_deduction_rate'];
                    $types = [
                        0 => '社区绿色积分',
                        1 => '礼包绿色积分',
                        2 => '推广绿色积分',
                        3 => '分红绿色积分',
                    ];
                    $msg = $types[$type].'兑换抵扣券';
                    $deduction = bcmul($communityAmount,$configSet['community_deduction_rate']*0.01,2);
                    MemberService::getInstance()->addFinanceLog($userId, 'change_add', $deduction, 8, $msg, $orderNo,1,0,0);
                }
            }

            //$charge = round($communityAmount * $totalRate * 0.01, 2);
            $charge = bcmul(bcmul($communityAmount, $percent, 2), 0.01, 2);
            $amount = bcsub($communityAmount, $charge, 2);
            $amount = bcsub($amount,$deduction,2);
            $data = [
                'user_id' => $userId,
                'amount' => $amount,
                'money' => $communityAmount,
                'percent' => $percent,
                'charge' => $charge,
                'remark' => '兑换个人余额',
                'order_no' => $orderNo,
                'audit_at' => date('Y-m-d H:i:s'),
                'status' => 1, //成功
                'type' => $type,
                'deduction' => $deduction,
                'deduction_rate' => $deductionRate,
            ];
            $id = CommunityWithdraw::getInstance()->insertGetId($data);
            if (!$id) {
                return false;
            }
            //扣除社区余额
            $data = [
                0 => '社区',
                1 => '礼包',
                2 => '推广',
                3 => '分红',
            ];
            $dataType = [
                0 => 'community',
                1 => 'packs',
                2 => 'spread',
                3 => 'bonus',
            ];
            $msg = $data[$type] . '绿色积分兑换个人余额，兑换记录' . $orderNo;
            $return = MemberService::getInstance()->addFinanceLog($userId, 'change', $communityAmount, 5, $msg, $orderNo, 1, $type);
            if (!$return) {
                Finance::getInstance()->rollback();
                return false;
            }

            //增加余额
            $msg = $data[$type] . '绿色积分兑换个人余额';
            $return = MemberService::getInstance()->addFinanceLog($userId, $dataType[$type] . '_withdraw', $amount, 1, $msg);
            if (!$return) {
                Finance::getInstance()->rollback();
                return false;
            }

            //减少手续费
            /*$msg = $data[$type] . '绿色积分兑换个人余额手续费，兑换记录' . $orderNo;
            $return = MemberService::getInstance()->addFinanceLog($userId, 'change', $charge, 1, $msg);
            if (!$return) {
                Finance::getInstance()->rollback();
                return false;
            }*/

        } catch (\Exception $e) {
            Finance::getInstance()->rollback();
            return false;
        }
        Finance::getInstance()->commit();
        return true;
    }

    public function txStr($type): string
    {
        $str = '';
        switch ($type) {
            case 1:
                $str = 'TXW';
                break;
            case 2:
                $str = 'TXA';
                break;
            case 3:
                $str = 'TXS';
                break;
        }
        return $str;
    }

    public function getTypeName($type): string
    {
        //1微信 2支付宝 3杉德
        $typeNameArr = [
            1 => '微信',
            2 => '支付宝',
            3 => '杉德钱包',
        ];
        return $typeNameArr[$type] ?? '';
    }

    public function withdraw($userId, $amount, $aliName, $aliAccount, $type, $finance): string
    {
        $orderNo = getNo($this->txStr($type));
        $msg = '提现到' . $this->getTypeName($type) . '，提现订单' . $orderNo;
        //$after = bcsub($finance['amount'], $amount, 2);
        try {
            $data = [
                'user_id' => $userId,
                'amount' => $amount,
                'remark' => $msg,
                'order_no' => $orderNo,
                'ali_name' => $aliName,
                'ali_account' => $aliAccount,
                'type' => $type,
            ];
            $id = MemberWithdraw::getInstance()->insertGetId($data);
            if (!$id) {
                return '';
            }
            //扣除社区余额
            $return = MemberService::getInstance()->addFinanceLog($userId, 'change', $amount, 1, $msg, $orderNo);
            if (!$return) {
                return '';
            }
        } catch (\Exception $e) {
            return '';
        }
        return $orderNo;
    }

    /**
     * @param $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunityInfo($userId): array
    {
        $info = CommunityUserInfo::getInstance()->where(['user_id' => $userId])->find();
        if (empty($info)) {
            $info = [
                'currency_money' => 0,
                'user_id' => $userId,
                'avail_money' => 0,
                'freeze_money' => 0,
            ];
            CommunityUserInfo::getInstance()->insert($info);
        } else {
            $info = $info->toArray();
        }

        return $info;
    }

    /**
     * 社区列表
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCommunityList($type, $page, $pageSize): array
    {
        switch ($type) {
            case 1:
                $field = 'user_amount,id,community_name,address,shop_amount,shop_num';
                $list = CommunityUser::getInstance()
                    ->order('user_amount desc')
                    ->limit(($page - 1) * $pageSize, $pageSize)
                    ->field($field)
                    ->select();
                $list = empty($list) ? [] : $list->toArray();
                break;
            default:
                $list = [];
        }
        return $list;
    }

    /**
     * @param $settlementTime
     * @return array
     */
    public function getTimeInfo($settlementTime): array
    {
        $time = date('Hi');
        $inPay = false;
        $start = '';
        $end = '';
        foreach ($settlementTime as $val) {
            list($start, $end) = explode('-', $val); //去空格
            $startTime = str_replace(':', '', $start);
            $endTime = str_replace(':', '', $end);
            if ($time <= $endTime) {
                if ($startTime <= $time) {
                    $inPay = true;
                }
                break;
            }
        }
        return ['inPay' => $inPay, 'start' => $start, 'end' => $end];
    }

    /**
     * 社区类型列表
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getCateList(): array
    {
        $field = 'id,title,value';
        $where = [
            'deleted' => 0,
            'status' => 0,
            'type' => 0,
        ];
        $list = CommunityCate::getInstance()->where($where)->field($field)->order('sort desc,id asc')->select();
        return empty($list) ? [] : $list->toArray();
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function isNew($userId): bool
    {
        $newCount = $this->getCommunityConfig('new_count');
        $where = [
            ['status', 'in', [1, 2]],
            ['user_id', '=', $userId]
        ];
        $count = CommunityOrder::getInstance()->where($where)->count();
        if ($count && $count >= $newCount) {
            return false;
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function orderTimeout($orderId): bool
    {
        $where = [
            ['id', '=', $orderId]
        ];
        $communityOrder = CommunityOrder::getInstance()->where($where)->find();
        if (empty($communityOrder)) {
            return false;
        }
        //1未支付订单
        if ($communityOrder['status'] != 1) {
            return false;
        }
        $communityOrder->status = 3;
        $communityOrder->updateAt = date('Y-m-d H:i:s');
        $communityOrder->save();
        //更新社区
        $communityUser = CommunityUser::getInstance()->where('community_id', $communityOrder->communityId)->find();
        if ($communityUser && in_array($communityUser['communityStatus'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS, CommunityConst::BUY_STATUS])) {
            $communityUser->communityStatus = $communityUser['userId'] > 0 ? CommunityConst::RELEASE_STATUS : CommunityConst::CAN_STATUS;
            //$communityUser->updateAt = date('Y-m-d H:i:s');
            $communityUser->save();
            RedisCache::hMSet(KeysUtil::getCommunityInfo($communityOrder->communityId), CommonUtil::camelToUnderLine($communityUser->toArray()));
        }
        return true;
    }

    public function prepayOrderTimeout($orderId): bool
    {
        $where = [
            ['id', '=', $orderId]
        ];
        $prepayCommunityOrder = PrepayCommunityOrder::getInstance()->where($where)->find();
        if (empty($prepayCommunityOrder)) {
            return false;
        }
        //1未支付订单
        if ($prepayCommunityOrder['status'] != 1) {
            return false;
        }
        $prepayCommunityOrder->status = 3;
        $prepayCommunityOrder->updateAt = date('Y-m-d H:i:s');
        $prepayCommunityOrder->save();
        //退款
        return true;
    }

    public function newTimeout()
    {
        RedisCache::del(KeysUtil::getCommunityPayListKey(1));
        $where = [
            ['lock_status', '=', 2],
            ['community_status', 'in', [0, 1, 3]],
            ['type', '=', 1]
        ];
        CommunityUser::getInstance()->where($where)->update(['type' => 0]);
    }

    public function prepayTimeout(): bool
    {
        PrepayCommunityOrder::getInstance()->startTrans();
        try{
            RedisCache::del(KeysUtil::getCommunityPayListKey(4));
            $where = [
                ['lock_status', '=', 2],
                ['community_status', 'in', [0, 1, 3]],
                ['type', '=', 4]
            ];
            CommunityUser::getInstance()->where($where)->update(['type' => 0]);

            $where = [
                ['status','=',2],
                ['is_final','=',0]
            ];
            $data = [
                'is_turn' => 1,
                'update_at' => date('Y-m-d H:i:s')
            ];
            PrepayCommunityOrder::getInstance()->where($where)->update($data);
            PrepayCommunityOrder::getInstance()->commit();
        }catch (\Exception $e){
            Log::error('[prepayTimeout]'.$e->getMessage());
            PrepayCommunityOrder::getInstance()->rollback();
        }
        return true;
    }

    /**
     * @throws DbException
     */
    public function improveRate($userId,$orderId = 0): array
    {
        $checkingCriterion = $this->getCommunityConfig('checking_criterion');
        if (empty($checkingCriterion) || empty($checkingCriterion['data']) || $checkingCriterion['status'] == 0) {
            return [0, 0];
        }
        $improveUserPremiumRate = 0;
        $improveTransferRate = 0;
        foreach ($checkingCriterion['data'] as $v) {
            switch ($v['task_type']) {
                case 1:
                    //推荐会员
                    $where = [
                        ['create_at','>=',date('Y-m-d')],
                        ['invite_id','=',$userId],
                        ['community_order_id','=',$orderId],
                    ];
                    $count = Member::getInstance()->where($where)->count();
                    if($count > 0 && $v['task_money'] > 0){
                        $count = 0;
                        $userIds = Member::getInstance()->where($where)->column('id');
                        foreach($userIds as $uid){
                            $where = [
                                ['user_id', '=', $uid],
                                ['status', '=', 1],
                                ['order_status', 'in', [0,5,6]],
                                ['create_at','>=',date('Y-m-d')]
                            ];
                            $money = OrderPay::getInstance()->where($where)->sum('pay_price') ?: 0;
                            if($money >= $v['task_money']){
                                $count += 1;
                            }
                        }
                    }
                    break;
                case 2:
                    //推荐商家
                    //推荐商家奖励5%，被推荐的商家，当日流水满X元
                    $where = [
                        ['invite_id', '=', $userId],
                        ['is_shop', '=', 1],
                        ['community_order_id','=',$orderId],
                        ['create_at','>=',date('Y-m-d')]
                    ];
                    $ids = Member::getInstance()->where($where)->column('id');
                    $count = 0;
                    if(!empty($ids)){
                        $where = [
                            ['user_id','in',$ids],
                            ['status','=',1],
                            ['auth_at','>=',date('Y-m-d')],
                            ['create_at','>=',date('Y-m-d')]
                        ];
                        $shopIds = Shop::getInstance()->where($where)->column('id');
                        $count = !empty($shopIds) ? count($shopIds) : 0;
                        if($count > 0 && $v['task_money'] > 0){
                            $count = 0;
                            foreach($shopIds as $shopId){
                                //1待发货 2待收款 3已收货 4已完成
                                $where = [
                                    ['shop_id','=',$shopId],
                                    ['status','in',[1,2,3,4]],
                                    ['create_at','>=',date('Y-m-d')]
                                ];
                                $money = OrderShop::getInstance()->where($where)->sum('pay_price') ?: 0;
                                if($money >= $v['task_money']){
                                    $count += 1;
                                }
                            }
                        }
                    }
                    break;
                case 3:
                    //平台消费
                    $where = [
                        ['user_id', '=', $userId],
                        ['status', '=', 1],
                        ['order_status', 'in', [0,5,6]],
                        ['community_order_id','=',$orderId]
                    ];
                    if($v['task_money'] > 0){
                        $where[] = ['pay_price','>=',$v['task_money']];
                    }
                    $count = OrderPay::getInstance()->where($where)->count() ?: 0;
                    break;
                case 4:
                    //观看广场
                    $where = [
                        ['log_type', '=', 'adv'],
                        ['user_id', '=', $userId],
                        ['order_id', '=', $orderId]
                    ];
                    $count = CommunityTaskLog::getInstance()->where($where)->count();
                    break;
                default:
                    $count = 0;
            }
            $status = $count >= $v['task_num'] ? 1 : 0;
            $task = $this->tasksLog($count,$orderId,$userId,$v['task_type'],$status);
            if (isset($task['completeNum']) && $task['completeNum'] >= $v['task_num']) {
                if ($v['award_type'] == 1) {
                    //提升会员溢价收益比
                    $improveUserPremiumRate += $v['award_num'] ?? 0;
                } else {
                    //提升转让溢价比
                    $improveTransferRate += $v['award_num'] ?? 0;
                }
            }
        }
        return [$improveUserPremiumRate, $improveTransferRate];
    }

    public function HaPayCallback($payInfo, $data, $communityOrder, $communityUser): bool
    {
        $date = date('Y-m-d H:i:s');
        $userIds = empty($communityUser['userIds']) ? (";" . $communityOrder['userId'] . ";") : ($communityUser['userIds'] . $communityOrder['userId'] . ";");
        $communityOrder['premium'] = !empty($communityOrder['premium']) ? $communityOrder['premium'] : 0;
        $communityUserData = [
            'user_amount' => bcadd($communityUser['userAmount'], $communityOrder['premium'], 2),
            'user_ids' => $userIds,
            'community_status' => CommunityConst::PERMANENT_STATUS,
            'lock_status' => CommunityConst::LOCK,
            'user_id' => $communityOrder['userId'],
            'last_enter_amount' => $communityOrder['price'],
            'last_order_id' => $communityOrder['id'],
            'last_enter_time' => $date,
            'total_amount' => $communityOrder['totalAmount'],
            'permanent_time' => $date
        ];

        $isCommunityUser = CommunityUser::getInstance()->where(['id' => $communityUser['id']])->update($communityUserData);
        if (!$isCommunityUser) {
            return false;
        }
        $orderDate = [
            'status' => CommunityConst::ORDER_PAY,
            'pay_at' => $date,
            'pay_price' => $payInfo['payPrice'],
            'amount_price' => $payInfo['communityPayAmount'],
            'sign_price' => $payInfo['signPrice'],
            'trade_no' => $data['trade_no'],
        ];
        $where = [
            ['order_no', '=', $payInfo['orderNo']],
            ['status', '=', CommunityConst::ORDER_NO_PAY]
        ];
        $isCommunityOrder = CommunityOrder::getInstance()->where($where)->update($orderDate);
        if (!$isCommunityOrder) {
            return false;
        }
        $ret = $this->addCommunityLockLog($communityOrder['userId'],$communityUser['communityId'],$communityUser['communityName'],$communityOrder['id']);
        if (!$ret) {
            return false;
        }
        return true;
    }

    /**
     * @param $payInfo
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function getCommunityInviteMoneyHall($payInfo): bool
    {
        $order = $this->getOrder($payInfo['orderNo']);
        if (empty($order)) {
            return false;
        }
        $orderNo = $payInfo['orderNo'];
        CommunityUser::getInstance()->where(['community_id' => $order['communityId']])->inc('user_amount', $order['premium']);
        if (!$order['lastOrderId']) {
            return false;
        }
        $lastOrder = $this->getLastCommunityOrder($order['lastOrderId']);
        if (empty($lastOrder)) {
            return false;
        }
        //上次购买本金、收益转余额
        $msg = "社区转让，获得购买本金";
        $price = $lastOrder['totalAmount'];

        //非平台社区奖励开启后，若社区有归属人，则按原溢价奖励规则
        //开始
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        /*$premium = bcmul($order['price'],$config['buy_award_rate']*0.01,2);
        if($config['buy_platform_status'] == 1){
            $premium = bcsub($order['price'],$price,2);
        }*/

        if($order['lastOrderId'] == 0){
            $premium = bcmul($order['price'],$config['buy_award_rate']*0.01,2);
        }else{
            $price = CommunityOrder::getInstance()->where('id',$order['lastOrderId'])->value('total_amount') ?: 0 ;
            //有归属人
            $premium = bcsub($order['price'],$price,2);
        }

        //裂变订单 本金、溢价收益拆分
        if ($lastOrder['isFission']) {
            Log::info($orderNo . '获得购买本金' . $price);
            $price = bcmul($lastOrder['totalAmount'], 0.5, 2);
        }
        //杉德支付，本金兑换到电子钱包
        MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'community_principal', $price, 1, $msg, $orderNo);
        $msg = "兑换到电子钱包";
        MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'change_bag', $price, 1, $msg, $orderNo);

        //非平台社区奖励关闭，不赠送收益，开启才赠送
        if($config['buy_platform_status'] == 1){
            //社区溢价收益
            $serviceEarnings = $this->getCommunityConfig('member_settlement_rate');

            $msg = "社区转让，获得社区溢价收益，收益比例" . $serviceEarnings . '%，转让订单' . $orderNo . '，';
            $premiumPrice = bcmul(bcmul($premium, $serviceEarnings, 4), 0.01, 4);
            Log::info($orderNo . '招募大厅社区溢价收益' . $premiumPrice);
            MemberService::getInstance()->addFinanceLog($lastOrder['userId'], 'community_premium', $premiumPrice, 3, $msg, $orderNo);
        }


        $price = env('test.is_test') ? 0.01 : $price;
        $ret = SandService::getInstance()->transfer($price, env('sand.consumeMid'), SandConst::PREFIX . $lastOrder['userId'], 0, getNo(OrderPrefixConst::TR));
        if (!isset($ret['code']) || $ret['code'] != 1) {
            throw new Exception($orderNo . $ret['data']);
        }

        //赠送贡献值
        //$msg = '社区竞拍，赠送贡献值，订单' . $payInfo['orderNo'];
        //MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'community', $premium, 7, $msg, $payInfo['orderNo']);
        return true;
    }

    /**
     * 招募大厅社区溢价分红
     * @param $communityUser
     * @param $orderNo
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function dividendHall($communityUser, $orderNo): bool
    {
        $where = [
            'community_id' => $communityUser['communityId'],
        ];
        $order = CommunityOrder::getInstance()->where($where)->where('pay_at', 'not null')->order('id desc')->find();
        if (empty($order)) {
            return false;
        }
        /*if($order['lastOrderId'] == 0){
            return true;
        }*/
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if(isset($config['buy_award_status']) && $config['buy_award_status'] == 1){
            if($config['buy_award_gxz'] > 0){
                //赠送贡献值
                $msg = '社区竞拍，赠送贡献值，订单' . $orderNo;
                $gxz = bcmul($order['price'],$config['buy_award_gxz'] * 0.01,2);
                MemberService::getInstance()->addFinanceLog($order['userId'], 'community', $gxz, 7, $msg, $orderNo);
            }
            if(!empty($config['buy_award_coupon_ids'])){
                CouponService::getInstance()->sendCouponByIds($order['userId'],$config['buy_award_coupon_ids']);
            }
        }

        //没归属人
        if($order['lastOrderId'] == 0){
            $order['premium'] = bcmul($order['price'],$config['buy_award_rate']*0.01,2);
        }else{
            $price = CommunityOrder::getInstance()->where('id',$order['lastOrderId'])->value('total_amount') ?: 0 ;
            //有归属人
            $order['premium'] = bcsub($order['price'],$price,2);
        }
        //加入分润池
        MemberService::getInstance()->profitPoolLog($order['userId'], $order['price'], $orderNo, $order['premium'], 4);

        //非平台社区奖励开启后，若社区有归属人，则按原溢价奖励规则
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if(isset($config['buy_platform_status']) && $config['buy_platform_status'] == 0){
            //未开启
            return true;
        }

        //服务商收益
        //获取服务商
        $partnerInfo = MemberService::getInstance()->getMyPartnerInfo($order['userId']);
        if ($partnerInfo) {
            //获取服务商溢出收益百分比
            $serviceEarnings = $this->getCommunityConfig('service_earnings');
            $msg = "社区转让，获得服务商收益，收益比例" . $serviceEarnings . '%，';
            $price = bcmul(bcmul($order['premium'], $serviceEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['partnerId'], 'service_earnings', $price, 3, $msg, $orderNo);
        }

        $member = Member::getInstance()->where('id', $order['userId'])->find();
        if (empty($member)) {
            return false;
        }

        //下级服务商团队社区溢价的2%举例说明:关系 A->B->C->D A,C 为服务商 ，D买了一个溢价社区，C拿溢价的8% A溢价的2%
        $myPartner = MemberService::getInstance()->getMyPartner($member);
        if ($myPartner) {
            //获取服务商团队溢出收益百分比
            $serviceTeamEarnings = $this->getCommunityConfig('service_team_earnings');
            $msg = "社区转让，获得服务商团队收益，收益比例" . $serviceTeamEarnings . '%，';
            $price = bcmul(bcmul($order['premium'], $serviceTeamEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($myPartner['id'], 'service_team_earnings', $price, 3, $msg, $orderNo);
        }

        //活动奖励
        if(isset($config['buy_activity_award_status']) && $config['buy_activity_award_status'] == 1) {
            //直推奖励
            if ($config['buy_activity_direct_award'] > 0) {
                $inviteId = RedisCache::hGet(KeysUtil::getMemberInfoKey($order['userId']), 'invite_id');
                if($inviteId){
                    $userName = RedisCache::hGet(KeysUtil::getMemberInfoKey($order['userId']), 'user_name');
                    $msg = '直推会员'.$userName.'购买'.$communityUser['communityName'].'奖励，';
                    $price = $config['buy_activity_direct_award'];
                    MemberService::getInstance()->addFinanceLog($inviteId, 'operate_activity_earnings', $price, 3, $msg, $orderNo);
                }
            }
            //服务商奖励
            if ($config['buy_activity_service_award'] > 0) {
                $getMyService = MemberService::getInstance()->getMyService($member);
                if($getMyService){
                    $userName = RedisCache::hGet(KeysUtil::getMemberInfoKey($order['userId']), 'user_name');
                    $msg = '团队会员'.$userName.'购买'.$communityUser['communityName'].'奖励，';
                    $price = $config['buy_activity_service_award'];
                    MemberService::getInstance()->addFinanceLog($getMyService['id'], 'operate_activity_earnings', $price, 3, $msg, $orderNo);
                }
            }
        }

        CommunityOrder::getInstance()->where(['id' => $order['lastOrderId']])->update(['next_order_id' => $order['id']]);

        //省市区收益
        //获取社区的省市区代 极差
        $communityPartnerInfo = MemberService::getInstance()->getCommunityAgencyInfo($order['communityId']);
        if ($communityPartnerInfo['provinceUid'] > 0) {
            //$provinceEarnings = $communityPartnerInfo['provinceEarnings'];
            $provinceEarnings = CommunityService::getInstance()->getCommunityConfig('province_community_earnings');
            $msg = "社区转让，获得区域（" . $communityPartnerInfo['provinceName'] . "）社区转让收益，收益比例" . $provinceEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $provinceEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($communityPartnerInfo['provinceUid'], 'province_community_earnings', $price, 3, $msg, $orderNo);
        }
        if ($communityPartnerInfo['cityUid'] > 0) {
            //$cityEarnings = $communityPartnerInfo['cityEarnings'];
            $cityEarnings = CommunityService::getInstance()->getCommunityConfig('city_community_earnings');
            $msg = "社区转让，获得区域（" . $communityPartnerInfo['cityName'] . "）社区转让收益，收益比例" . $cityEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $cityEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($communityPartnerInfo['cityUid'], 'city_community_earnings', $price, 3, $msg, $orderNo);
        }
        if ($communityPartnerInfo['countryUid'] > 0) {
            //$areaEarnings = $communityPartnerInfo['areaEarnings'];
            $areaEarnings = CommunityService::getInstance()->getCommunityConfig('area_community_earnings');
            $msg = "社区转让，获得区域（" . $communityPartnerInfo['countryName'] . "）社区转让收益，收益比例" . $areaEarnings . '%,转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $areaEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($communityPartnerInfo['countryUid'], 'area_community_earnings', $price, 3, $msg, $orderNo);
        }

        //获取用户的省市区代 极差
        $partnerInfo = MemberService::getInstance()->getMyAgencyInfo($order['userId']);
        if ($partnerInfo['provinceUid'] > 0) {
            //$provinceEarnings = $partnerInfo['provinceEarnings'];
            $provinceEarnings = CommunityService::getInstance()->getCommunityConfig('province_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['provinceName'] . "）会员竞拍收益，收益比例" . $provinceEarnings . '%，转让订单' . $orderNo . ',';
            $price = bcmul(bcmul($order['premium'], $provinceEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['provinceUid'], 'province_user_earnings', $price, 3, $msg, $orderNo);
        }
        if ($partnerInfo['cityUid'] > 0) {
            //$cityEarnings = $partnerInfo['cityEarnings'];
            $cityEarnings = CommunityService::getInstance()->getCommunityConfig('city_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['cityName'] . "）会员竞拍收益，收益比例" . $cityEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $cityEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['cityUid'], 'city_user_earnings', $price, 3, $msg, $orderNo);
        }
        if ($partnerInfo['countryUid'] > 0) {
            //$areaEarnings = $partnerInfo['areaEarnings'];
            $areaEarnings = CommunityService::getInstance()->getCommunityConfig('area_earnings');
            $msg = "社区转让，区域（" . $partnerInfo['countryName'] . "）会员竞拍收益，收益比例" . $areaEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $areaEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($partnerInfo['countryUid'], 'area_user_earnings', $price, 3, $msg, $orderNo);
        }

        //事业部收益获取事业部列表
        $businessList = $this->getUserBusinessUser();
        foreach ($businessList as $val) {
            $incomeRate = $val['incomeRate'];
            $msg = "社区转让，获得事业部收益，收益比例" . $incomeRate . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $incomeRate, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($val['userId'], 'business_earnings', $price, 3, $msg, $orderNo);
        }

        //vip用户收益
        $inviteId = $member['inviteId'];
        $vipUser = $this->getParentVipUser($inviteId);
        $vipEarnings = $this->getCommunityConfig('vip_earnings');
        if ($vipUser) {
            $msg = "社区转让，获得VIP收益，收益比例" . $vipEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $vipEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($vipUser['id'], 'vip_earnings', $price, 3, $msg, $orderNo);
        }

        //用户社区合伙人
        $recruitPartnerEarnings = CommunityService::getInstance()->getCommunityConfig('recruit_partner_earnings');
        $commId = Community::getInstance()->where('comm_id', $member['commId'])->value('id');
        $where  = [
            ['community_id', '=', $commId],
            ['community_status', '=', CommunityConst::PERMANENT_STATUS],
        ];
        $community = CommunityUser::getInstance()->where($where)->find();
        if($recruitPartnerEarnings > 0 && !empty($community) && $community['userId']) {
            $msg = "社区转让，获得社区合伙人收益，收益比例" . $recruitPartnerEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $recruitPartnerEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($community['userId'], 'recruit_partner_earnings', $price, 3, $msg, $orderNo);
        }

        //直推
        $recruitDirectEarnings = CommunityService::getInstance()->getCommunityConfig('recruit_direct_earnings');
        if($inviteId){
            $msg = "社区转让，获得直推收益，收益比例" . $recruitDirectEarnings . '%，转让订单' . $orderNo . '，';
            $price = bcmul(bcmul($order['premium'], $recruitDirectEarnings, 4), 0.01, 4);
            MemberService::getInstance()->addFinanceLog($inviteId, 'recruit_direct_earnings', $price, 3, $msg, $orderNo);
        }
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public function OcPayCallback($payInfo): bool
    {
        $where = [
            ['order_no', '=', $payInfo['orderNo']],
        ];
        $data = [
            'is_pay' => 1,
            'pay_at' => date('Y-m-d H:i:s'),
        ];
        $order = CommunityOpOrder::getInstance()->where($where)->update($data);
        if ( ! $order) {
            return false;
        }

        $opOrder = CommunityOpOrder::getInstance()->where($where)->find();
        if ( ! $opOrder) {
            return false;
        }

        //更新社区
        $time = date('Y-m-d H:i:s');
        $data = [
            'community_status' => CommunityConst::PERMANENT_STATUS,
            'is_pay_service'   => CommunityConst::PAY_SERVICE,
            'permanent_time'   => $time,
            'is_op_transfer'   => 0,
            'lock_status'      => CommunityConst::LOCK,
            'user_id'          => $payInfo['userId'],
            'total_amount'     => $opOrder['payPrice'],
            'last_enter_amount' => $opOrder['payPrice'],
            'update_at' => $time,
            'last_enter_time' => $time,
            'type' => 3,
        ];
        $communityUser = CommunityUser::getInstance()->where('op_order_no', $payInfo['orderNo'])->update($data);
        if ( ! $communityUser) {
            return false;
        }

        if ($payInfo['communityPayAmount'] > 0) {
            $msg = '购买转让社区,支付金额:' . $payInfo['communityPayAmount'];
            MemberService::getInstance()->addFinanceLog($opOrder['payUserId'], 'pay_oc', $payInfo['communityPayAmount'], 1, $msg, $payInfo['orderNo']);
        }

        $order = CommunityOpOrder::getInstance()->where('order_no',$payInfo['orderNo'])->find();
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if(isset($config['transfer_award_status']) && $config['transfer_award_status'] == 1){
            if($config['transfer_award_gxz'] > 0){
                //赠送贡献值
                $msg = '购买转让社区，赠送贡献值';
                $gxz = bcmul($order['payPrice'],$config['transfer_award_gxz'] * 0.01,2);
                MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'community_oc', $gxz, 7, $msg, $payInfo['orderNo']);
            }
            if(isset($config['transfer_award_coupon_status']) && $config['transfer_award_coupon_status'] == 1){
                if(!empty($config['transfer_award_coupon_ids'])){
                    CouponService::getInstance()->sendCouponByIds($payInfo['userId'],$config['transfer_award_coupon_ids']);
                }
            }
        }

        //公司杉德账号转账给用户
        $fee = bcmul($order['payPrice'], bcmul($order['serviceRate'], 0.01, 2), 2);
        //扣除平台收取服务费
        $price = bcsub($order['payPrice'], $fee, 2);
        OrderError::getInstance()->insert(['text' => $payInfo['orderNo'] . '购买转让社区公司杉德账号转账给用户' . $price]);
        Log::info($payInfo['orderNo'] . '购买转让社区公司杉德账号转账给用户' . $price);
        $price = env('test.is_test') ? 0.01 : $price;
        $ret = SandService::getInstance()->transfer($price, env('sand.consumeMid'), SandConst::PREFIX . $opOrder['userId'], 0, getNo(OrderPrefixConst::TR));
        if (!isset($ret['code']) || $ret['code'] != 1) {
            throw new Exception($payInfo['orderNo'] . $ret['data']);
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function PrPayCallback($payInfo): bool
    {

        $where = [
            ['order_no', '=', $payInfo['orderNo']],
            ['status','=',1] //未支付
        ];
        $prepayCommunityOrder = PrepayCommunityOrder::getInstance()->where($where)->find();
        if(empty($prepayCommunityOrder)){
            return false;
        }
        $data = [
            'status' => 2,
            'pay_at' => date('Y-m-d H:i:s'),
        ];
        $order = PrepayCommunityOrder::getInstance()->where($where)->update($data);
        if (!$order) {
            return false;
        }
        if ($payInfo['communityPayAmount'] > 0) {
            $msg = '竞拍社区抵扣:' . $payInfo['communityPayAmount'];
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'pay_community', $payInfo['communityPayAmount'], 1, $msg, $payInfo['orderNo']);
        }
        return true;
    }

    public function taskForAdv($userId,$communityId,$orderId): bool
    {
        $data = [
            'community_id' => $communityId,
            'order_id' => $orderId,
            'user_id' => $userId,
            'log_type' => 'adv'
        ];
        CommunityTaskLog::getInstance()->insert($data);
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function communityBusiness($orderNo): bool
    {
        if(!$orderNo){
            return false;
        }
        $communityOpOrder = CommunityOpOrder::getInstance()->field('order_id,community_id')->where('order_no',$orderNo)->find();
        if(empty($communityOpOrder)){
            return false;
        }
        if($communityOpOrder['isBusinessProfit'] == 1){
            return false;
        }
        $where = [
            'community_id' => $communityOpOrder['communityId'],
        ];
        $order = CommunityOrder::getInstance()->where($where)->where('pay_at', 'not null')->order('id desc')->find();
        if (empty($order)) {
            return false;
        }
        $data = RedisCache::get(KeysUtil::getCommunityBusinessKey());
        if(empty($data)){
            $businessList = $this->getUserBusinessUser();
            if(empty($businessList)){
                return false;
            }
            $data = json_encode($businessList,256);
            RedisCache::setEx(KeysUtil::getCommunityBusinessKey(),5*60,$data);
        }
        $list = json_decode($data,1);

        Finance::getInstance()->startTrans();
        try{
            foreach ($list as $val) {
                $incomeRate = $val['incomeRate'];
                $msg = "社区转让，获得事业部收益，收益比例" . $incomeRate . '%，转让订单' . $orderNo . '，';
                $price = bcmul(bcmul($order['premium'], $incomeRate, 4), 0.01, 4);
                MemberService::getInstance()->addFinanceLog($val['userId'], 'business_earnings', $price, 3, $msg, $orderNo);
            }
            Finance::getInstance()->commit();
            $communityOpOrder->isBusinessProfit = 1;
            $communityOpOrder->updateAt = date('Y-m-d H:i:s');
            $communityOpOrder->save();
        }catch (\Exception $e){
            Log::error($orderNo.'事业部分红:'.$e->getMessage());
            Finance::getInstance()->rollback();
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function createCommunityUser($communityId, $userId, $price): bool
    {
        $community = Community::getInstance()->where('id',$communityId)->find();
        $community->lock_status = 2;
        $ret = $community->save();
        if(!$ret){
            return false;
        }
        $data = [
            'community_name' => $community['name'],
            'community_id' => $community['id'],
            'address' => $community['province'] . $community['city'] . $community['country'] . $community['street'],
            'user_id' => $userId,
            'last_enter_amount' => $price,
            'community_status' => CommunityConst::PERMANENT_STATUS,
            'lock_status' => CommunityConst::LOCK,
            'last_order_id' => 0,
            'is_pay_service' => 0,
            'total_amount' => $price,
            'activity_id' => 0,
            'type' => 3, //招募广场
        ];
        $ret = CommunityUser::getInstance()->insert($data);
        if(!$ret){
            return false;
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function everyTransferCount($userId){
        $count = 0;
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');
        if(isset($transferConfig['status']) && $transferConfig['status'] == 1){
            $where = [
                ['user_id','=',$userId],
                ['status','=',1],
                ['deleted','=',0],
            ];
            $agencyType = MemberAgency::getInstance()->where($where)->value('agency_type') ?? 0;
            if($agencyType == 1){
                return $transferConfig['province_count'] ?? 0;
            }

            if($agencyType == 2){
                return $transferConfig['city_count'] ?? 0;
            }

            if(in_array($agencyType,[3,4])){
                return $transferConfig['area_count'] ?? 0;
            }
            $isPartner = Member::getInstance()->where('id',$userId)->value('is_partner');
            if($isPartner){
                return $transferConfig['service_count'] ?? 0;
            }
            return $transferConfig['user_count'] ?? 0;
        }
        return $count;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function transferMaxMoney($userId){
        $money = 0;
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');
        if(isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
            $now = date('Y-m-d H:i:s');
            if($now < $transferConfig['start_time'] || $now > $transferConfig['end_time']){
                return $money;
            }
            $where = [
                ['user_id','=',$userId],
                ['status','=',1],
                ['deleted','=',0],
            ];
            $agencyType = MemberAgency::getInstance()->where($where)->value('agency_type') ?? 0;
            if($agencyType == 1){
                return $transferConfig['province_money'] ?? 0;
            }

            if($agencyType == 2){
                return $transferConfig['city_money'] ?? 0;
            }

            if(in_array($agencyType,[3,4])){
                return $transferConfig['area_money'] ?? 0;
            }
            $isPartner = Member::getInstance()->where('id',$userId)->value('is_partner');
            if($isPartner){
                return $transferConfig['service_money'] ?? 0;
            }
            return $transferConfig['user_money'] ?? 0;
        }
        return $money;
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function addTransferCount($userId,$orderNo): bool
    {
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');
        if(empty($transferConfig)){
           return false;
        }
        if(empty($transferConfig['start_time']) || empty($transferConfig['end_time'])){
            return false;
        }
        $now = date('Y-m-d H:i:s');
        if($now < $transferConfig['start_time'] || $now > $transferConfig['end_time']){
            return false;
        }
        MemberInfoService::getInstance()->memberNum($userId);
        if(isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
            //所有
            $where = [
                ['user_id','=',$userId],
                ['community_status','=',6],
                ['last_enter_time','>=',date('Y-m-d')]
            ];
            $num = CommunityUser::getInstance()->where($where)->count();
            if($transferConfig['all_limit_count'] > 0){
                if($num < $transferConfig['all_limit_count']){
                    MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                    return true;
                }
                return false;
            }
            $where = [
                ['user_id','=',$userId],
                ['status','=',1],
                ['deleted','=',0],
            ];
            $agencyType = MemberAgency::getInstance()->where($where)->value('agency_type') ?? 0;
            //省
            if($agencyType == 1){
                if($transferConfig['province_limit_count'] > 0 && $num <= $transferConfig['province_limit_count']){
                    MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                    return true;
                }
            }

            //市
            if($agencyType == 2){
                if($transferConfig['city_buy_count'] > 0){
                    if($transferConfig['city_limit_count'] > 0 && $num <= $transferConfig['city_buy_count']){
                        MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                        return true;
                    }
                }
            }
            //区
            if(in_array($agencyType,[3,4])){
                if($transferConfig['area_limit_count'] > 0 && $num <= $transferConfig['area_limit_count']){
                    MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                    return true;
                }
            }
            //服务商
            $isPartner = Member::getInstance()->where('id',$userId)->value('is_partner') ?: 0;
            if($agencyType <= 0 && $isPartner > 0){
                if($transferConfig['service_limit_count'] > 0 && $num <= $transferConfig['service_limit_count']){
                    MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                    return true;
                }
            }
            //普通会员
            if($agencyType <= 0 && $isPartner == 0 && $transferConfig['user_limit_count'] > 0 && $num <= $transferConfig['user_limit_count']){
                MemberInfoService::getInstance()->addCommunityTransferCount($userId,1,1,$orderNo);
                return true;
            }
        }
        return false;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function tasksLog($completeNum, $orderId, $userId, $type, $status): array
    {
        $where = [
            ['type','=',$type],
            ['community_order_id','=',$orderId],
            ['status','=',1]
        ];
        $task = CommunityTasksLog::getInstance()->where($where)->find();
        if($task){
            return !empty($task) ? $task->toArray() : [];
        }
        $where = [
            ['type','=',$type],
            ['community_order_id','=',$orderId],
        ];
        $task = CommunityTasksLog::getInstance()->where($where)->find();
        if($task){
            CommunityTasksLog::getInstance()->where($where)->update(['update_at'=> date('Y-m-d H:i:s'),'complete_num' => $completeNum,'status' => $status]);
        }else{
            $where = [
                ['status','=',1],
                ['community_order_id','=',$orderId]
            ];
            $orderNo = OrderPay::getInstance()->where($where)->order('id desc')->value('order_no') ?? '';
            $data = [
                'complete_num' => $completeNum,
                'type' => $type,
                'community_order_id' => $orderId,
                'user_id' => $userId,
                'status' => $status,
                'order_no' => $orderNo,
            ];
            CommunityTasksLog::getInstance()->insert($data);
        }
        $task = CommunityTasksLog::getInstance()->where($where)->find();
        return !empty($task) ? $task->toArray() : [];
    }

    public function addCommunityLockLog($userId,$communityId,$communityName,$lastOrderId){
        $lockData = [
            'user_id' => $userId,
            'community_id' => $communityId,
            'community_name' => $communityName,
            'order_id' => $lastOrderId,
        ];
        return CommunityLockLog::getInstance()->insert($lockData);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function actionCount($userId): bool
    {
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');

        if(isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
            $where = [
                ['user_id','=',$userId],
                ['community_status','in',[4,6]],
                ['last_enter_time','>=',date('Y-m-d')]
            ];
            $num = CommunityUser::getInstance()->where($where)->count();
            //所有
            if($transferConfig['all_buy_count'] > 0 && $transferConfig['all_limit_count'] > 0){
                if($num >= $transferConfig['all_buy_count']){
                    return false;
                }
                return true;
            }
            $where = [
                ['user_id','=',$userId],
                ['status','=',1],
                ['deleted','=',0],
            ];
            $agencyType = MemberAgency::getInstance()->where($where)->value('agency_type') ?? 0;
            //省
            if($agencyType == 1){
                if($transferConfig['province_buy_count'] > 0){
                    if($num >= $transferConfig['province_buy_count'] && $transferConfig['province_limit_count'] > 0){
                        return false;
                    }
                }
            }
            //市
            if($agencyType == 2){
                if($transferConfig['city_buy_count'] > 0){
                    if($num >= $transferConfig['city_buy_count'] && $transferConfig['city_limit_count'] > 0){
                        return false;
                    }
                }
            }
            //区
            if(in_array($agencyType,[3,4])){
                if($transferConfig['area_buy_count'] > 0){
                    if($num >= $transferConfig['area_buy_count'] && $transferConfig['area_limit_count'] > 0){
                        return false;
                    }
                }
            }
            //服务商
            $isPartner = Member::getInstance()->where('id',$userId)->value('is_partner') ?: 0;
            if($agencyType <= 0 && $isPartner > 0 && $transferConfig['service_buy_count'] > 0){
                if($num >= $transferConfig['service_buy_count'] && $transferConfig['service_limit_count'] > 0){
                    return false;
                }
            }
            //普通会员
            if($agencyType <= 0 && $isPartner == 0 && $num >= $transferConfig['user_buy_count'] && $transferConfig['user_limit_count'] > 0){
                return false;
            }
        }
        return true;
    }


}


